export const isBorderAround = (range, sheet) => {
    const borderTop = range.borderTop();
    let borderBottom = range.borderBottom();
    const borderLeft = range.borderLeft();
    let borderRight = range.borderRight();
    if (range.colCount > 1) {
        borderRight = sheet.getRange(range.row, range.col + range.colCount - 1, range.rowCount, 1).borderRight();
    }
    if (range.rowCount > 1) {
        borderBottom = sheet.getRange(range.row + range.rowCount - 1, range.col, 1, range.colCount).borderRight();
    }
    return !!(borderTop && borderTop.style !== GC.Spread.Sheets.LineStyle.empty &&
        borderBottom && borderBottom.style !== GC.Spread.Sheets.LineStyle.empty &&
        borderLeft && borderLeft.style !== GC.Spread.Sheets.LineStyle.empty &&
        borderRight && borderRight.style !== GC.Spread.Sheets.LineStyle.empty);
}

export const getNextColBorderedRanges = (sheet, cellRange, rangeRowCounts, isInDetails) => {
    const length = rangeRowCounts.length;
    const ranges = [];
    let startRow = cellRange.row;
    const startCol = cellRange.col + cellRange.colCount;
    const span = sheet.getSpan(startRow, startCol);
    let firstRange;
    if (span) {
        firstRange = sheet.getRange(span.row, span.col, span.rowCount, span.colCount);
    } else {
        firstRange = sheet.getRange(startRow, startCol, 1, 1);
    }
    cellRange = firstRange;
    for (let index = 0; index < length; index++) {
        const span1 = sheet.getSpan(startRow, startCol);
        let range;
        if (span1) {
            range = sheet.getRange(span1.row, span1.col, span1.rowCount, span1.colCount);
        } else {
            range = sheet.getRange(startRow, startCol, 1, 1);
        }
        const rowCount = rangeRowCounts[index];
        if (range.col === startCol && range.rowCount === rowCount && !isInDetails(range.row, range.col) && isBorderAround(range, sheet)) {
            ranges.push(rowCount);
        } else {
            break;
        }
        startRow += rowCount;
    }
    return [ranges, firstRange];
}

export default (sheet, cellRange, isInDetails) => {
    const ranges = [];
    let range = cellRange;
    let { row } = cellRange;
    const { col, colCount } = cellRange;
    do {
        ranges.push(range.rowCount);
        row = range.row + range.rowCount;
        const span = sheet.getSpan(row, col);
        if (span) {
            range = sheet.getRange(span.row, span.col, span.rowCount, span.colCount);
        } else {
            range = sheet.getRange(row, col, 1, 1);
        }
        if (range.value()) {
            break;
        }
    } while (range.col === col && range.colCount === colCount && !isInDetails(range.row, range.col) && isBorderAround(range, sheet))
    return ranges;
}